<?php

class Point extends AppModel {
  var $belongsTo = array(
    'Sender' => array(
      'className' => 'User',
      'foreignKey' => 'sender_id',
    ),
    'User' => array(
      'className' => 'User', 
      'foreignKey' => 'user_id',
      'counterCache' => 'point_count',
      /*'counterScope' => array('visible' => TRUE),*/
    ),
  );

  /*
  Does not work as fields might not even be included
  var $validate = array(
    'sender_name' => array(
      'rule' => 'validateSender',
      'required' => TRUE,
      'message' => 'Gib einen Namen als Absender an.',
    ),
    'name' => array(
      'rule' => 'validateRecipient',
      'required' => TRUE,
      'message' => 'Gib Name & E-Mail-Adresse des Empfängers an.',
    ),  
  );
  */

  function beforeValidate($options) {
    if ($options['validate']) {
      return $this->validateSender() && $this->validateRecipient();
    }
    else {
      return TRUE;
    }
  }

  /**
   * Make sure either sender_id or sender is set.
   */
  function validateSender() {
    if ($this->id) {
      // always validates on UPDATE
      return TRUE;
    }
    if (@$this->data['Point']['sender_id'] || @$this->data['Point']['sender_name']) {
      return TRUE;
    }
    else {
      $this->validationErrors['sender_name'] = 'Gib einen Namen als Absender an.';
      return FALSE;
    }
  }

  /**
   * Make sure either user_id or name/email is set.
   */
  function validateRecipient() {
error_log("recipient " . json_encode($this->data));
    if (@$this->data['Point']['user_id'] || (@$this->data['Point']['name'] && @$this->data['Point']['email'])) {
      return TRUE;
    }
    else {
      $this->validationErrors['name'] = 'Gib Name und E-Mail-Adresse des Empfängers an.';
      return FALSE;
    }
  }

  function afterSave($created) {
    if (!$created) {
      return;
    }
    $unique = FALSE;
    while (!$unique) {
      $code = base_convert(rand(), 10, 36);
      $unique = $this->save(array('code' => $code));
    }

    /*
     * Sender
     */
    if (isset($this->data['Point']['sender_id'])) {
      $sender = $this->User->find('first', array('conditions' => array('User.id' => $this->data['Point']['sender_id'])));
      $sender_name = $sender['User']['name'];
    }
    else {
      $sender_name = $this->data['Point']['sender_name'];
    }

    /*
     * Recipient
     */
    if (isset($this->data['Point']['user_id'])) {
      $recipient = $this->User->find('first', array('conditions' => array('User.id' => $this->data['Point']['user_id'])));
      $recipient_email = $recipient['User']['email'];
    }
    else {
      $recipient_email = $this->data['Point']['email'];
    }

    App::import('Component', 'Email');

    $link = 'http://' . $_SERVER['HTTP_HOST'] . '/p/' . $code;

    $addresses = array('Alle Achtung', 'Wow', 'Hut ab', 'Prima', 'Toll');
    $address = $addresses[rand(0, count($addresses) - 1)];

    $email = new EmailComponent;
    $email->to = $recipient_email;
    $email->from = $sender_name . ' <info@browniepoints.de>';
    $email->subject = 'Ein Browniepunkt von ' . $sender_name;
    $email->send("{$address},

{$sender_name} hat dir einen Browniepunkt geschickt.
Um ihn zu aktivieren, klicke auf den folgenden Link:

{$link}

Dein Browniepunkt-Depot.");
  }

  function afterFind($results, $primary = FALSE) {
    foreach ($results as $i => $result) {
      if (@$result['sender_id']) {
        $sender = $this->User->find('first', array(
          'conditions' => array('User.id' => $result['sender_id']),
          'recursive' => -1));
        $results[$i]['Sender'] = $sender['User'];
      }
    }
    return $results;
  }
}